﻿using System;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;

namespace CRMWeb.Utilities
{
	public static class CryptographyHelper {

        public static string EncodePassword(string password)
        {
            return EncodePassword(password, MembershipPasswordFormat.Hashed);
        }

        public static string EncodePassword(string password, MembershipPasswordFormat PasswordFormat)
        {
            string encodedPassword = password;
            switch (PasswordFormat)
            {
                case MembershipPasswordFormat.Clear:
                    break;
                case MembershipPasswordFormat.Encrypted:
                    //encodedPassword =
                    //  Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
                    break;
                case MembershipPasswordFormat.Hashed:
                    HMACSHA1 hash = new HMACSHA1();
                    hash.Key = Encoding.Unicode.GetBytes(password);
                    encodedPassword =
                      Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
                    break;
                default:
                    throw new Exception("Unsupported password format.");
            }
            return encodedPassword;
        }

        // HashAlgorithm -> KeyedHashAlgorithm -> HMAC -> HMACSHA256
        // http://www.freeformatter.com/hmac-generator.html
        public static string EncryptStringHMACSHA256(string inputString, string keyString)
        {
            byte[] bytKey = Encoding.UTF8.GetBytes(keyString); //UTF-8 is required for above website
            byte[] bytInput = Encoding.UTF8.GetBytes(inputString);
            HashAlgorithm algorithm = new HMACSHA256(bytKey);
            byte[] outputBytes = algorithm.ComputeHash(bytInput);
            var hex = BitConverter.ToString(outputBytes);
            return hex.Replace("-", "").ToLower();
        }
        /*Not possible with hexadecimal key use cipher text encryption or use AES/AESmanage for both encryption and decryption */
        public static string DecryptStringHMACSHA256(string inputString, string keyString)
        {
            return "#scgsfgsfd";
            //byte[] bytKey = Encoding.UTF8.GetBytes(keyString); //UTF-8 is required for above website
            //byte[] bytInput = Encoding.UTF8.GetBytes(inputString);
            //HashAlgorithm algorithm = new HMACSHA256(bytKey);
            //byte[] outputBytes = algorithm.ComputeHash(bytInput);
            //var hex = BitConverter.ToString(outputBytes);
            //return hex.Replace("-", "").ToLower();
        }
	}
}